/**
 * 获取小程序用户数据
 */
const Auth = {}

/**
 * 获取当前登陆用户信息
 * @return {object}
 */
Auth.user = function() {
  return wx.getStorageSync('user');
}

/**
* 获取token
* @return {string}
*/
Auth.token = function() {
  return wx.getStorageSync('token');
}

/**
* 判断是否有效期
* @return {boolean}
*/
Auth.check = function() {
  let chckFlag = false;
  let user = Auth.user()
  let token = Auth.token()
  // 验证session_key过期时间
  let sessionFlg = Auth.checkSession();
  // 验证access_token过期时间
  if (user && Date.now() < wx.getStorageSync('expired_in') && token) {
      console.log('access_token过期时间：', (wx.getStorageSync('expired_in') - Date.now()) / 1000, '秒');
      chckFlag =  true;
  } else {
    chckFlag =  false;
  }
  return chckFlag || sessionFlg
}

/**
 * 检查登录态是否过期
 */
Auth.checkSession = function() {
  let flag = false;
    wx.checkSession({
      success: function(res) {
        flag = true;
      },
      fail: function(err) {
        flag = false;
      }
  });
  return flag;
}

/**
* 登录
* @return {Promise} 登录信息
*/
Auth.login = function() {
  return new Promise(function(resolve, reject) {
      wx.login({
          success: function(res) {
              resolve(res);
          },
          fail: function(err) {
              reject(err);
          }
      });
  });
}

/**
* 注销
* @return {boolean}
*/
Auth.logout = function() {
  wx.removeStorageSync('user')
  wx.removeStorageSync('token')
  wx.removeStorageSync('expired_in')
  return true
}

/**
* 获取授权登录加密数据
*/
Auth.getMiniEncryptedData = function(){
  return new Promise(function(resolve, reject) {
  // Auth.login().then(data => {
    let args = {}
    // args.code = data.code;
    args.code = wx.getStorageSync('js_code');
    wx.getUserInfo({
      success: function (res) {
        console.log('getUserInfo->', res);
        //args.iv = encodeURIComponent(res.iv);
        //args.encryptedData = encodeURIComponent(res.encryptedData);
        args.iv = res.iv;
        args.encryptedData = res.encryptedData;
        args.rawData = res.rawData;
        args.signature = res.signature;
        resolve(args);
      },
      fail: function (err) {
        reject(err);
      }
    });
  //})
  });
}

module.exports = Auth